package com.it.park.controller.expose;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.client.service.IntegralConsumeService;
import com.it.park.client.service.NoticeService;
import com.it.park.client.service.ResouceFileService;
import com.it.park.client.service.ResourceCollectionService;
import com.it.park.client.service.ResourceDownloadRecordService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.common.SessionUtil;
import com.it.park.constant.Constant;
import com.it.park.model.IntegralConsume;
import com.it.park.model.Notice;
import com.it.park.model.ResourceCollection;
import com.it.park.model.ResourceDownloadRecord;
import com.it.park.model.ResourceFile;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.UserService;
import com.it.park.util.empty.EmptyUtil;
import com.it.park.util.file.FileUtil;

/**
 * @author Administrator
 *资源下载
 */
@Controller
@RequestMapping("/expose/resource")
public class ExposeResourceController {
	private String rootPath=Constant.EXPOSE_PATH;

	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ResouceFileService resouceFileService;
	@Autowired
	private UserService userService;
	@Autowired
	private ResourceDownloadRecordService downloadRecordService;
	@Autowired
	private ResourceCollectionService resourceCollectionService;
	@Autowired
	private IntegralConsumeService consumeService;
	
	private Page page = null;
	
	@RequestMapping("listRows")
	@ResponseBody
	public Map<String,Object> listRows(HttpServletRequest request){
			List<Notice> list = noticeService.selectAll();
			int count = list.size();
			Map<String,Object> map  =new HashMap<String, Object>();
			map.put("total", count);
			map.put("rows", list);
			return map;
	}
	
	@RequestMapping("list")
	public String list(@RequestParam("pageNow") Integer pageNow,HttpServletRequest request){
			List<Notice> notices =	null;
			Map<String,Object> map = new HashMap<String, Object>();
			Integer total = noticeService.selectTotal(map);
			if(pageNow != null){
				page = new Page(pageNow,total,10);
			}else{
				page = new Page(1,total,10);
			}
			map.put("startPos", page.getStartPos());
			map.put("pageSize", page.getPageSize());
			notices = noticeService.listRelUser(map);
			request.setAttribute("totals", total);
			request.setAttribute("page", page);
			request.setAttribute("notices", notices);
			
			return rootPath+"notice/noticeList";
	}
	
	/**
	 *单个下载详情 
	 */
	@RequestMapping("detail")
	public String detail(@RequestParam("id") Integer id,HttpServletRequest request,HttpSession session){
		ResourceFile  rf = resouceFileService.selectByPrimaryKey(id);
		request.setAttribute("rf", rf);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("resourceType", rf.getResourceType());
		map.put("id", id);
		map.put("resourceTitle", rf.getResourceTitle());
		List<ResourceFile> rfsList =  resouceFileService.selectByTitle(map);
		request.setAttribute("rfsList", rfsList);
		return rootPath+"resource/resourceDetail";
	}
	
	/**
	 * 查询下载该资源需要的积分
	 */
	@RequestMapping("getResourceScore")
	@ResponseBody
	public JsonObj getResourceScore(@RequestParam("id") Integer id,HttpSession session){
		JsonObj json = new JsonObj();
		User user = SessionUtil.getSessionUser(session);
		if(user != null){
			ResourceFile rf = resouceFileService.selectByPrimaryKey(id);
			ResourceDownloadRecord record = new ResourceDownloadRecord();
			record.setUserId(user.getId());
			record.setResourceId(id);
			ResourceDownloadRecord r = downloadRecordService.selectByObject(record);
			if(r != null){
				json.setSuccess(true);
				json.setMessage("你已经下载过该资源，重复下载将不再扣积分!");
				json.setCode(103);
				return json;
			}
			User u = userService.selectByPrimaryKey(user.getId());
			if((u.getIntegral()-rf.getScore()) <0){
				json.setSuccess(false);
				json.setMessage("对不起,你的积分不够,请获取积分后在下载!");
				json.setObject(user.getIntegral());
				json.setCode(104);
			}else{
				String path = rf.getFilePath();
				if(EmptyUtil.isEmpty(path)){
					json.setSuccess(false);
					json.setMessage("对不起,该文件已经不存在了!");
					json.setCode(101);
				}else{
					json.setSuccess(true);
					json.setMessage("");
					json.setCode(100);
				}
			}
		}else{
			json.setSuccess(false);
			json.setMessage("对不起，你还未登录，请登录后再操作!");
			json.setCode(102);
		}
		return json;
	}
	
	/**
	 *单个资源下载
	 */
	@RequestMapping("downloadResource")
	public String downloadResource(@RequestParam("id") Integer id,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		User user = SessionUtil.getSessionUser(session);
			ResourceFile rf = resouceFileService.selectByPrimaryKey(id);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
				//设置输出长度
		        response.setHeader("Content-Length", rf.getResourceSize()); 
		        String fileName =rf.getResourceTitle()+"."+rf.getFileType();
		        response.reset();//清除response中的缓存信息
				try {
					response.setHeader("Content-Disposition", "attachment;fileName="+new String(fileName.getBytes("utf-8"),"iso-8859-1"));
					FileUtil.getBytes(rf.getFilePath());
					//统计下载次数
					int downloadCount = rf.getDownloadCount();
					rf.setDownloadCount(downloadCount+1);
					resouceFileService.updateByPrimaryKeySelective(rf);
					ResourceDownloadRecord record = new ResourceDownloadRecord();
					record.setUserId(user.getId());
					record.setResourceId(id);
					ResourceDownloadRecord r = downloadRecordService.selectByObject(record);
					if(r == null){
						//下载的时候扣除积分,已经下载过的不重复扣
						int jifen = user.getIntegral();
						user.setIntegral(jifen-rf.getScore());
						userService.updateByPrimaryKeySelective(user);
						//记录下载的资源
						downloadRecordService.insertSelective(record);
						//消费记录
						IntegralConsume consume = new IntegralConsume();
						consume.setCategory(0);
						consume.setCreateDate(new Date());
						consume.setReason("下载");
						consume.setUserId(user.getId());
						consume.setResourceId(id);
						consume.setIntegral(rf.getScore());
						consumeService.insertSelective(consume);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		return null;
	}
	
	/**
	 * 资源收藏
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/collectionResource")
	@ResponseBody
	public JsonObj collectionResource(@RequestParam("id") Integer id,HttpSession session){
		JsonObj json = new JsonObj();
		User user = SessionUtil.getSessionUser(session);
		if(user != null){
			ResourceCollection record = new ResourceCollection();
			record.setUserId(user.getId());
			record.setResourceId(id);
			record.setCollectionDate(new Date());
			ResourceCollection r = resourceCollectionService.selectByObject(record);
			if(r != null){
				json.setSuccess(false);
				json.setCode(103);
				json.setMessage("你已收藏过，请勿重复收藏!");
			}else{
				boolean success =	resourceCollectionService.insertSelective(record);
				if(success){
					json.setSuccess(true);
					json.setMessage("恭喜你,收藏成功!");
					json.setCode(100);
				}else{
					json.setSuccess(true);
					json.setMessage("很遗憾,收藏失败!");
					json.setCode(101);
				}
			}
		}else{
			json.setSuccess(false);
			json.setMessage("对不起，你还未登录，请登录后再操作!");
			json.setCode(102);
		}
		return json;
	}
	
	
}
